package com.plugin.uniapp.video;

import android.os.Handler;
import android.os.Looper;
import android.view.Surface;

import com.plugin.uniapp.Config;
import com.plugin.uniapp.MainActivity;
import com.plugin.uniapp.dialog.MultiViewDialog;
import com.plugin.uniapp.utils.Logger;
import com.plugin.uniapp.utils.WebSocketClient;

import okio.ByteString;

public class SurfacePlayer {
    public String deviceId;
    private Handler handler = new Handler(Looper.getMainLooper());
    private H264Decoder decoder;
    private WebSocketClient websocket;
    private String wsUrl;
    private Surface surface;
    private int retryTimes = 3;

    H264Decoder.NeedReconnectCallback needReconnectCallback = new H264Decoder.NeedReconnectCallback() {
        @Override
        public void onNeedReconnect() {
            log("先断网络,5秒后重连网络");
            websocket.disconnect();
            handler.postDelayed(() -> {
                if (MainActivity.instance != null) {
                    boolean canRetry = true;
                    if (MultiViewDialog.instance != null) {
                        canRetry = deviceId.equals(Config.lockedDeviceId);
                    }
                    if (canRetry) {
                        if (retryTimes > 0) {
                            retryTimes--;
                            start();
                        } else {
                            error("解码器初始化失败，已断网，且已尝试重连3次失败后不再尝试");
                        }
                    }
                }
            }, 5000);
        }
    };

    public SurfacePlayer(Surface surface, String deviceId) {
        this.surface = surface;
        this.deviceId = deviceId;
        this.decoder = new H264Decoder(deviceId);
        this.wsUrl = Config.WSBaseUrl + "/screen/" + deviceId;
        websocket = new WebSocketClient();
        websocket.addBytesCallback(bytes -> {
            //log("收到帧数据：" + bytes.length);
            decoder.pushBytes(bytes);
        });
    }

    public void start() {
        log("开始联网并播放");
        if (!decoder.isRunning) {
            decoder.start(surface, needReconnectCallback);
        }
        if (!websocket.isConnected) {
            websocket.connect(wsUrl, ()->{
                websocket.sendMessage(ByteString.of(new byte[]{17}));
            }, true);
        }
    }

    public void stop() {
        log("断网并停止播放");
        websocket.disconnect();
        decoder.stop();
    }

    public void changeSerface(Surface surface) {
        decoder.changeSurface(surface);
    }

    public void resumeSerface() {
        decoder.changeSurface(surface);
    }

    private void log(String msg) {
        //Logger.log("[" + deviceId + "]" + msg, getClass());
    }

    private void error(String msg) {
        //Logger.error("[" + deviceId + "]" + msg, getClass());
    }
}
